<template>
  <div class="user-list-container">
    <el-card shadow="hover">
      <template #header>
        <div class="header">
          <span>用户管理</span>
          <el-button type="primary" @click="openAddDialog">新增用户</el-button>
        </div>
      </template>

      <!-- 用户表格 -->
      <el-table :data="userList" border stripe style="width: 100%">
        <el-table-column prop="id" label="ID" width="300" />
        <el-table-column prop="userName" label="用户名" width="180" />
        <el-table-column prop="loginStatus" label="登录状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.loginStatus === 1 ? 'success' : 'info'">
              {{ row.loginStatus === 1 ? '在线' : '离线' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatTime(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="updateTime" label="更新时间" width="180">
          <template #default="{ row }">
            {{ formatTime(row.updateTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="{ row }">
            <el-button size="small" type="primary" @click="openEditDialog(row)">编辑</el-button>
            <el-button size="small" type="warning" @click="downStatus(row)">下线</el-button>
            <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 新增 / 编辑 用户对话框 -->
    <el-dialog :title="dialogTitle" v-model="dialogVisible" width="400px">
      <el-form :model="formData" :rules="rules" ref="formRef" label-width="90px">
        <el-form-item label="用户名" prop="userName">
          <el-input v-model="formData.userName" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="密码" prop="userPassword">
          <el-input v-model="formData.userPassword" type="password" placeholder="请输入密码" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import axios from 'axios'
import { baseHtpUrl } from '../js/baseUrl'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getUserList, createUser, updateUser, deleteUser, downUserStatus } from '../js/user'

// API 地址
const API_BASE = baseHtpUrl + '/api/users'

// 数据
const userList = ref([])
const dialogVisible = ref(false)
const dialogTitle = ref('')
const formRef = ref(null)

const formData = reactive({
  id: '',
  userName: '',
  userPassword: ''
})

const rules = {
  userName: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  userPassword: [{ required: true, message: '请输入密码', trigger: 'blur' }]
}

// 获取用户列表
const fetchUsers = async () => {
  // const res = await axios.get(API_BASE, {
  //   headers: {
  //     'token': localStorage.getItem('token')
  //   }
  // })
  const res = await getUserList()
  console.log('res', res)
  userList.value = res.data
}

// 打开新增对话框
const openAddDialog = () => {
  dialogTitle.value = '新增用户'
  formData.id = ''
  formData.userName = ''
  formData.userPassword = ''
  dialogVisible.value = true
}

// 打开编辑对话框
const openEditDialog = (row) => {
  dialogTitle.value = '编辑用户'
  formData.id = row.id
  formData.userName = row.userName
  formData.userPassword = ''
  dialogVisible.value = true
}

// 提交表单
const handleSubmit = () => {
  formRef.value.validate(async (valid) => {
    if (!valid) return
    try {
      if (formData.id) {
        // 编辑
        await updateUser(formData.id, {
          userName: formData.userName,
          userPassword: formData.userPassword
        })
        ElMessage.success('用户更新成功')
      } else {
        // 新增
        await createUser({
          userName: formData.userName,
          userPassword: formData.userPassword
        })
        ElMessage.success('用户创建成功')
      }
      dialogVisible.value = false
      fetchUsers()
    } catch (e) {
      console.log('e', e)
      ElMessage.error('操作失败')
    }
  })
}

const downStatus = (row) => {
  ElMessageBox.confirm(`确定下线用户 ${row.userName} 吗？`, '提示', {
    type: 'warning'
  })
    .then(async () => {
      await downUserStatus(row.id)
      ElMessage.success('下线成功')
      fetchUsers()
    })
    .catch(() => { })
}

// 删除用户
const handleDelete = (row) => {
  ElMessageBox.confirm(`确定删除用户 ${row.userName} 吗？`, '提示', {
    type: 'warning'
  })
    .then(async () => {
      await deleteUser(row.id)
      ElMessage.success('删除成功')
      fetchUsers()
    })
    .catch(() => { })
}

// 时间格式化
const formatTime = (timeStr) => {
  if (!timeStr) return ''
  return new Date(timeStr).toLocaleString()
}

// 初始化
onMounted(() => {
  fetchUsers()
})
</script>

<style scoped>
.user-list-container {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
